<?php

namespace App\Http\Controllers;

use App\GetPrizeByScan;
use App\Lottery;
use App\WechatShop;
use App\LotteryShop;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;

class LotteryController extends Controller
{
    // 微商铺编号
    protected $shopId;
    // 微商铺信息 from table wechat_shops
    protected $lotteryId;

    public function __construct(Request $request, WechatShop $wechatShop)
    {
        $this->lotteryId = $request->input('lottery_id') ? $request->input
        ('lottery_id') : 0;
        view()->share('lotteryId', $this->lotteryId);

    }
    /**
     * 抽奖对接程序
     *
     * @return view
     */
    public function index(){
        //$openID=session('wechat.user')->id;
        $openID='oUS4puPlHA53wkg2awtQhxeIMut0';
        //用户抽奖权限鉴定
        $prizeCheck = Lottery::where([
            'openID'=>$openID,
            'lottery_shop_id'=>$this->lotteryId,
        ])->first();
        $prizeData = LotteryShop::find($this->lotteryId);
        if($prizeCheck){
            if ($prizeCheck->prize!=0){
                $prizeTimes = 200;//已中过奖
                return view('lottery.index',compact('prizeTimes','prizeData'));
            }
            if ($prizeCheck->last_prize_date==Carbon::now()->format('d')){
                $prizeTimes = 0;//已抽过奖
                return view('lottery.index',compact('prizeTimes','prizeData'));
            }
        }
        $prizeTimes = 1;//可以抽奖
        //$prizeTimes = 0;//抽奖结束
        return view('lottery.index',compact('prizeTimes','prizeData'));
    }
    public function lotteryPost(Request $request){
        /*$wechat = app('wechat');
        $openID=session('wechat.user')->id;
        $user = $wechat->user->get(session('wechat.user')->id);
        $nickName=$user->nickname;*/
        $openID='oUS4puPlHA53wkg2awtQhxeIMut0';
        $nickName = "smallming";
        $lotteryId = $request->lotteryId;
        return $this->prizeStart($openID,$nickName,$lotteryId);
    }
    //抽奖程序
    public function prizeStart($openID,$nickName,$lotteryId){
        $prizeData = LotteryShop::find($lotteryId);
        $days =date('d',$prizeData['end_time'])-date('d', $prizeData['start_time']);
        $noPrizeNum = $prizeData['day_num']*$days-$prizeData['first_prize_num']
            -$prizeData['second_prize_num']-$prizeData['third_prize_num']
            -$prizeData['forth_prize_num'] -$prizeData['fivth_prize_num'];
        $prize_arr=[
            '0'=>['id'=>0,'min'=>[46,181,271,],'max'=>[89,224,314],'prize'=>'未中奖','v'=>$noPrizeNum],
            '1'=>['id'=>1,'min'=>316,'max'=>359,'prize'=>'一等奖','v'=>$prizeData['first_prize_num']],
            '2'=>['id'=>2,'min'=>91,'max'=>134,'prize'=>'二等奖', 'v'=>$prizeData['second_prize_num']],
            '3'=>['id'=>3,'min'=>226,'max'=>269,'prize'=>'三等奖', 'v'=>$prizeData['third_prize_num']],
            '4'=>['id'=>4,'min'=>136,'max'=>179,'prize'=>'四等奖', 'v'=>$prizeData['forth_prize_num']],
            '5'=>['id'=>5,'min'=>1,'max'=>44,'prize'=>'五等奖', 'v'=>$prizeData['fivth_prize_num']],
        ];

        $arr =[];
        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['v'];
        }
        //根据概率获取奖项id
        $rid = $this->getRand($arr);
        //判断奖品是否已经抽完
        $prizeLimit = $this->prizeLimit($rid,$arr,$days,$lotteryId);

        if ($prizeLimit){
            $result = $this->prize($openID,$nickName,$lotteryId,$prize_arr,$rid);
            $result['code']=$rid;
        }else{
            $result = $this->prize($openID,$nickName,$lotteryId,$prize_arr,0);
            $result['code']=0;
        }

        return json_encode($result);

    }

    public function prizeLimitForDay($num,$day){
        return  ceil($num/$day);
    }
    //奖品数量限制
    public function prizeLimit($rid,$arr,$days,$lotteryId){
        $count=Lottery::where([
            'prize'=>$rid,
            'lottery_shop_Id'=>$lotteryId,
        ])->count();
        $todayCount=Lottery::where([
            'prize'=>$rid,
            'lottery_shop_Id'=>$lotteryId,
            'last_prize_date'=>Carbon::now()->format('d'),
        ])->count();
        switch ($rid){
            case 1://一等奖数量
                if ($count>=$arr[1] || $todayCount >= $this->prizeLimitForDay
                    ($arr[1],$days))return false;
                return true;
                break;
            case 2://二等奖数量
                if ($count>=$arr[2]|| $todayCount >= $this->prizeLimitForDay
                    ($arr[2],$days))return false;
                return true;
                break;
            case 3://三等奖数量
                if ($count>=$arr[3]|| $todayCount >= $this->prizeLimitForDay
                    ($arr[3],$days))return false;
                return true;
                break;
            case 4://四等奖数量
                if ($count>=$arr[4]|| $todayCount >= $this->prizeLimitForDay
                    ($arr[4],$days))return false;
                return true;
                break;
            case 5://五等奖数量
                if ($count>=$arr[5]|| $todayCount >= $this->prizeLimitForDay
                    ($arr[5],$days))return false;
                return true;
                break;
            default:
                return false;
        };
        return false;

    }
    //封装中奖结果
    public function prize($openID,$nickName,$lotteryId,$prize_arr,$rid){
        $res = $prize_arr[$rid]; //中奖项
        $min = $res['min'];
        $max = $res['max'];

        if($res['id']==0){
            //未中奖
            $i = mt_rand(0,2);
            $result['angle'] = mt_rand($min[$i],$max[$i]);
        }else{
            $result['angle'] = mt_rand($min,$max); //随机生成一个角度
        }
        Lottery::updateOrCreate([
            'lottery_shop_id'=>$lotteryId,
            'openID'=>$openID,
        ],[
            'lottery_shop_id'=>$lotteryId,
            'openID'=>$openID,
            'nikeName'=>$nickName,
            'prize'=>$rid,
            'last_prize_date'=>Carbon::now()->format('d'),
            'status'=>0,
        ]);
        $result['prize'] = $res['prize'];
        return $result;
    }

    //中奖情况计算
    public function getRand($proArr) {
        $result = '';

        //概率数组的总概率精度
        $proSum = array_sum($proArr);

        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);

        return $result;
    }
    /**
     * 中奖结果展示
     *
     * @return view
     */
    public function showPrize(){
        //$openID=session('wechat.user')->id;
        $openID='oUS4puPlHA53wkg2awtQhxeIMut0';
        $prize=Lottery::where([
            'openID'=>$openID,
            'lottery_shop_id'=>$this->lotteryId,
        ])->first();
        $prizeData = LotteryShop::find($this->lotteryId);
        return view('lottery.showPrize',compact('prize','prizeData'));

    }
    public function prizeList(){
        $prizeList=Lottery::where('lottery_shop_id',$this->lotteryId)
            ->where(function($query){
                $query->where('prize','!=','0');
            })->take(50)->get();
        /*dd($prizeList);*/
        return view('lottery.prizeList',compact('prizeList'));
    }

    /**
     * 领奖
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getPrize(Request $request){
        $openID = $request->openID;
        $prize=Lottery::where([
            'openID'=>$openID,
            'lottery_shop_id'=>$this->lotteryId,
        ])->first();
        return view('lottery.getPrize',compact('prize'));

    }
    public function getPrizePost(Request $request){
        $prizeID = $request->prizeID;
        Lottery::find($prizeID)->update(['status'=>1]);
        return view('lottery.success');


    }
    public function success(){
        return view('lottery.success');
    }
    /**
     * 线下关注 领奖
     *
     * @return view
     */

    public function getPrizeByScan(){
        //  $openID=session('wechat.user')->id;
       $openID='oUS4puPlHA53wkg2awtQhxeIMut0';
        $user = GetPrizeByScan::where([
            'openID' => $openID,
            'lottery_shop_id'=>$this->lotteryId,
        ])->first();
        if($user){
            $type = 1;//已经领过奖品
            return view('lottery.getPrizeByScan',compact('type'));
        }
        $type = 0;
        return view('lottery.getPrizeByScan',compact('type'));

    }
    public function getPrizeByScanPost(Request $request){
        $lotteryId = $request->lotteryId;
        GetPrizeByScan::create([
            'lottery_shop_id' => $lotteryId,
            /*'openID'=>session('wechat.user')->id,*/
            'openID' => 'oUS4puPlHA53wkg2awtQhxeIMut0',
            'status' => 1,
        ]);
        return view('lottery.success');

    }
    /**
     * 未关注提示
     *
     * @return view
     */
    public function needFocus(){
        return view('lottery.needFocus');

    }
}
